package com.jzoom.zoom.admin.controllers;


import com.jzoom.zoom.admin.models.DaoService;
import com.jzoom.zoom.admin.models.DecorationTableService;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.dao.driver.DbStructFactory;
import com.jzoom.zoom.web.annotations.Controller;
import com.jzoom.zoom.web.annotations.JsonResponse;
import com.jzoom.zoom.web.annotations.Param;
import com.jzoom.zoom.web.exception.StatusException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 与结构有关的，如表结构、数据库结构、api结构等
 * @author jzoom
 *
 */
@JsonResponse
@Controller(key="structs")
public class StructsController {

	
	@Inject
	private DaoService daoService;
    @Inject
    private DecorationTableService tableDao;

    public List<Record> getApis(
            @Param(body = true) Map<String, Object> params) {
        return tableDao.getApis(params);
    }


    public Collection<DbStructFactory.TableNameAndComment> getTables(String ds, String table) {
		if(ds==null || table == null) {
			throw new StatusException.ApiError("参数不正确");
		}
		Dao dao = daoService.getDao(ds);
		if(dao==null) {
			throw new StatusException.ApiError("数据源"+ds+"不存在");
		}
		
		DbStructFactory factory = dao.getDbStructFactory();
		
		Collection<DbStructFactory.TableNameAndComment> records = factory.getNameAndComments(dao.ar());
		
		List<DbStructFactory.TableNameAndComment> list = new ArrayList<DbStructFactory.TableNameAndComment>();
		for (DbStructFactory.TableNameAndComment record : records) {
			String name = record.getName();
			if(StringUtils.contains(name, table)) {
				list.add(record);
			}
		}
		return list;
	}
	
	
	
	
}
